from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status

from .models import User, Group


class UserAPITest(APITestCase):

    @classmethod
    # it's better do not overwrite setUpClass
    # def setUpClass(cls):
    #     super().setUpClass()
    def setUpTestData(cls):
        cls.user = User.objects.create(email='person@example.com', username='Test user')

    def setUp(self) -> None:
        # login
        self.client.force_authenticate(user=self.user)

    def tearDown(self) -> None:
        # logout
        self.client.logout()

    # def test_1(self):
    #     self.assertTrue(1)
    #
    # def test_2(self):
    #     self.assertTrue(1)

    def test_list(self):
        user1 = User.objects.create(email='person2@example.com', username='Test user1')
        user2 = User.objects.create(email='person2@example.com', username='Test user2')

        response = self.client.get(reverse('user-list'))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(User.objects.filter(id=user1.id).exists())
        self.assertTrue(User.objects.filter(id=user2.id).exists())

    def test_add(self):
        response = self.client.post(reverse('user-list'), data={"username": "admin1"})
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_detail(self):
        user2 = User.objects.create(email='person2@example.com', username='user2')
        response = self.client.get(reverse('user-detail', args=[user2.id]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(response.data.get('username') == 'user2')

    def test_update(self):
        user2 = User.objects.create(email='person2@example.com', username='user2')
        response = self.client.put(reverse('user-detail', args=[user2.id]), data={"username": "user222"})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue(response.data.get('username') == 'user222')

    def test_delete(self):
        error_user = User.objects.create(email='person2@example.com', username='error_user')
        self.assertTrue(User.objects.filter(id=error_user.id).exists())
        response = self.client.delete(reverse('user-detail', args=[error_user.id]))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
        self.assertFalse(User.objects.filter(id=error_user.id).exists())
